<?php
defined('_JEXEC') or die;

$session_vipcard =& JFactory::getSession();
$session_vipcard_id =  $session_vipcard->getId();

$lang =& JFactory::getLanguage();

$page_heading = JText::_(WrdHelper::stringURLSafeAliasLang('WRD_PROMOTION_CATEGORY_'.$this->category_detail->title));
$title = JText::_('WMCVIP_TITLE_PREFIX').$page_heading.JText::_('WMCVIP_TITLE_SUFIX');
$document = &JFactory::getDocument();
$document->setTitle($title) ;

?>
<link rel="stylesheet" type="text/css" href="<?php echo JURI::base(); ?>js/multiselect/jquery-ui.css" />
<link type="text/css" href="<?php echo JURI::base(); ?>css/buttons.css" rel="stylesheet" />
<script type="text/javascript" src="<?php echo JURI::base(); ?>js/dialog/jquery-ui-1.8.20.custom.min.js"></script>
<script src="<?php echo JURI::base(); ?>js/number_format.js"></script>

<div class="row">
	<div class="twelve columns all_reward_header">
		<?php echo $page_heading; ?>
	</div>
</div>


<script type="text/javascript">
    var scItems = [];
    if(jQuery.cookie("<?php echo md5($session_vipcard_id); ?>") != ""){
    	var data_dec = decodeCookies(jQuery.cookie("<?php echo md5($session_vipcard_id); ?>"));
        scItems = json_decode(data_dec);
    }
    var currentUserPoint = "<?php echo $this->userPoint; ?>";    
    var totalPointSubtract = currentUserPoint;
    
    jQuery(function(){
	
        totalPointAndCash();
        
        jQuery.spin.imageBasePath = '<?php echo JURI::base(); ?>js/spin/images/spin2/';
        jQuery('.spin').spin({
            max: 10,
            min: 0
        });
			
		width = $(window).width();
        rig  = (width-985)/2 
		height = parseInt($(window).height());
		
		var h =  jQuery(window).scrollTop();
		
		jQuery(window).scroll(function(){
			h =  jQuery(window).scrollTop();
			jQuery("#point_eff").css({top: (h+height-81),right: rig});
		}); 
		
		jQuery("#point_eff").css({top: (h+height-81),right: rig});
        
		jQuery(".add-to-cart a").click(function(index){

            var objName = jQuery(this).attr("name");
            var item = {
                id:     0,
                qty:    0,
                pcode:  0,
                type:   1,
                img:    '',
                point:  0,
                pointx: 0,
                cash:   0,
                name: '',
                ptotal:  1
            };
            
            params  = objName.split("_");            
            item.id = params[1];
            var inputName = jQuery("input[name="+objName+"_type]:checked").attr("id");
            item.type = jQuery("#"+inputName).val();
           
            if(jQuery("input[name="+objName+"_type]:checked").length == 0){
			
                alert("<?php echo JText::_('WRD_PROMOTION_PLEASE_CHOOSE_RWWRD_PROMOTION_EDEMPTION_TYPE') ?>");
                return false;
				
            }
            else {
                var qty = jQuery("input[name="+inputName+"_qty]").val();
				var productPoint = 0;
				
                if(item.type == 1) {
				
                    item.point = jQuery("#"+inputName+"_point").val();  
                    item.cash = 0;
                    item.pointx = 0;
                    productPoint = (parseInt(qty)*parseInt(item.point));
					
                }
                else {
				
                    item.point = 0;
                    item.pointx = jQuery("#"+inputName+"_pointx").val();
                    item.cash = jQuery("#"+inputName+"_cash").val();  
                    productPoint = (parseInt(qty)*parseInt(item.pointx));  
                }
                if(qty <= 0){
                    alert("Please input a valid value!");
                    return false;
                }
                else {
                    var subtractPoint = 0;
                    if(scItems != null && scItems.length > 0){
                        for(var i=0; i<scItems.length; i++){
                            if(item.id == scItems[i].id){
                               	
                                totalPointSubtract = parseInt(totalPointSubtract) + (parseInt(scItems[i].qty)*parseInt(scItems[i].type == 1 ? scItems[i].point : scItems[i].pointx));
                            }
                        }
                    }
                    
                    var subtractPoint = totalPointSubtract;
                    subtractPoint = parseInt(subtractPoint) - parseInt(productPoint);
                        
                    if(subtractPoint < 0){
					
                        alert("<?php echo JText::_('WRD_PROMOTION_YOUR_POINT_IS') ?> "+(totalPointSubtract)+" < " + productPoint+" <?php echo JText::_('WRD_PROMOTION_IS_NOT_ENOUGHT_TO_REDEEM') ?>");
                        
                    }
                    else {

						var update = true;
						var ptotal = 0;
						
						item.qty = parseInt(qty);
                        item.img = jQuery("#"+objName+"_img").attr("src");
                        item.pcode = jQuery("#"+objName+"_code").html();
                        nameItem = jQuery("#item_"+item.id+"_name").val();
                        item.name = objName;
                        

                        if(scItems != null && scItems.length > 0){
                            
                            for(var i=0; i<scItems.length; i++){                                
                                if(scItems[i].id == item.id) {
                                    if(scItems[i].type != item.type) {
                                       update = false;
                                    }else{
                                        item.qty = parseInt(scItems[i].qty) + 1;
                                        scItems[i] = item;
                                        update = true;
                                        break;
                                    }
                                    
                                }else{
                                    update = false;
                                }
                            }
                            
                            if(update == false) {
                                scItems.push(item);
                            }
                        }
                        else {
                            if(scItems ==  null){
                                scItems = new Array();
                                scItems[0] = item;
                            } else {
                                scItems.push(item);    
                            }
                        }
                    }
                }
            }
            
            for(var i=0; i<scItems.length; i++){
                if(scItems[i].id == item.id) {
                    ptotal = parseInt(ptotal) + parseInt(scItems[i].qty);
                }
            }
            
            /*** Process Data ***/
            item.ptotal = ptotal;
            var page_refresh = false;
            jQuery.ajax({
            	async: false,
                type: "post",
                url : "<?php echo utilitiesProvider::rewriteGlobalUrl('index.php?option=com_promotions&layout=addtocart&view=redemptions'); ?>",
                data: "params="+json_encode(item),
                success: function(json){
                    var result = eval(json);
                    //console.log("Result: "+json_encode(result));
                    if (result.success == true)
                    {

						//var total_item = 0;
						totalPointAndCash();
						
						//show effect
						jQuery("#point_eff").show().animate({top: (h+height-350)}, 1500, 'swing', function() {
                
                            jQuery("#point_eff").css({opacity: 0.25}).fadeOut( 1000, function() {
                            
                                jQuery(this).css({top: (h+height-81), opacity: 1});  
                            }); 
                        });
                    }
                    else
                    {
						
						if(result.refresh == true) page_refresh = true;
                        if(scItems != null && scItems.length > 0){
                            for(var i=0; i<scItems.length; i++){
                                if(scItems[i].id == item.id) {
                                    //scItems[i].ptotal = item.ptotal;
                                    if(scItems[i].type == item.type){
                                        
                                         item.qty =  parseInt(result.allow);
                                    
                                        if(item.qty <= 0){
                                            scItems.splice(i,1);
                                        }
                                    }
                                    
                                }
                            }
                        }
                        
                        totalPointAndCash();
                        if(result.html != '')
                        	alert(result.html);
                        
                    }
                }
                
               
            }); 
            
            var data_enc = encodeCookies(scItems);
			jQuery.cookie("<?php echo md5($session_vipcard_id); ?>", json_encode(data_enc), { expires: 1, path: '/' });   
            
            if(page_refresh == true){
            	location.reload(true);
            }
            return true;
        });
        
    });

	function encodeCookies(obj){
		var data ;
    	jQuery.ajax({
    		async: false,
            type: "post",
            url : "<?php echo utilitiesProvider::rewriteGlobalUrl('index.php?option=com_promotions&task=encryptcart'); ?>",
            data: "params="+json_encode(obj),
            success: function(json){ 
                var result = eval(json);
                
                if (result.success == true)
                {
                	data =  result.data;
                }
                else
                {
                	//console.log('security hole');
                }
            }
        });
        
        return data;
    }
    
    function decodeCookies(obj){
    	var data ;
    	jQuery.ajax({
    		async: false,
            type: "post",
            url : "<?php echo utilitiesProvider::rewriteGlobalUrl('index.php?option=com_promotions&task=decryptcart'); ?>",
            data: "params="+(obj),
            success: function(json){ 
                var result = eval(json);
                
                if (result.success == true)
                {
                	data =  result.data;
                }
                else
                {
                	//console.log('can not decrypt');
                }
            }
        });
        return data;
    }
    
    function totalPointAndCash(){
	
        var totalPoint = 0;
        var totalCash = 0;
        //console.log(scItems);
        if(scItems != null && scItems.length > 0){
        	var total_item = 0;
            for(var i=0; i<scItems.length; i++){
				totalPoint = parseInt(totalPoint) + parseInt(scItems[i].point)*parseInt(scItems[i].qty) + parseInt(scItems[i].pointx)*parseInt(scItems[i].qty);
				totalCash = parseInt(totalCash) + parseInt(scItems[i].cash)*parseInt(scItems[i].qty); 
				total_item = total_item + parseInt(scItems[i].qty);
            }
            
            totalPointSubtract = parseInt(currentUserPoint) - parseInt(totalPoint);
            
            var html = "<table style=\"width: 100%;\" cellpadding=\"0\" cellspacing=\"0\"><tbody>";
            html += "<tr><td width=\"50%\" align=\"right\"><?php echo JText::_('WRD_LEFT_MENU_YOUR_POINTS') ?> </td><td width=\"50%\" align=\"left\">"+number_format(totalPointSubtract, 0,',',',')+"</td></tr>";
            html += "<tr><td width=\"50%\" align=\"right\"><?php echo JText::_('WRD_LEFT_MENU_TOTAL_POINTS') ?> </td><td width=\"50%\" align=\"left\">"+number_format(totalPoint, 0,',',',')+"</td></tr>";
            
            html += "<tr><td align=\"right\"><?php echo JText::_('WRD_LEFT_MENU_TOTAL_CASH') ?> </td><td align=\"left\">"+number_format(totalCash, 0,',',',')+"</td></tr>";
            html += "</tbody></table>";
            
            if(total_item <= 1)
				jQuery("#cart-items").html('<span class="item_count">'+total_item+'</span><span class="item_text"><?php echo JText::_('WRD_LEFT_MENU_ITEM_IN_YOUR_CART') ?></span>');
			else
				jQuery("#cart-items").html('<span class="item_count">'+total_item+'</span><span class="item_text"><?php echo JText::_('WRD_LEFT_MENU_ITEMS_IN_YOUR_CART') ?></span>');
				            	
            jQuery("#invoice-details").html(html); 
            jQuery("#redeem-now-link").show(); 
        }
        else{
        	var html = "<table style=\"width: 100%;\" cellpadding=\"0\" cellspacing=\"0\"><tbody>";
            html += "<tr><td width=\"50%\" align=\"right\"><?php echo JText::_('WRD_LEFT_MENU_YOUR_POINTS') ?> </td><td width=\"50%\" align=\"right\">"+number_format(currentUserPoint, 0,',',',')+"</td></tr>";
            html += "<tr><td width=\"50%\" align=\"right\"><?php echo JText::_('WRD_LEFT_MENU_TOTAL_POINTS') ?> </td><td width=\"50%\" align=\"right\">"+number_format(0, 0,',',',')+"</td></tr>";
            
            html += "<tr><td align=\"right\"><?php echo JText::_('WRD_LEFT_MENU_TOTAL_CASH') ?> </td><td align=\"right\">"+number_format(0, 0,',',',')+"</td></tr>";
            html += "</tbody></table>";
            
			jQuery("#cart-items").html('<span class="item_count">0</span><span class="item_text"><?php echo JText::_('WRD_LEFT_MENU_ITEM_IN_YOUR_CART') ?></span>');

            jQuery("#invoice-details").html(html);
            jQuery("#redeem-now-link").hide();
		}
    }
    
    
    
</script>
<?php
if (count($this->items) > 0) :
?>
<div class="member-area">
    <form class="custom" action="<?php echo JRoute::_("index.php?option=com_promotions&view=redemptions")?>" method="post" name="adminForm" >
    <?php 
        foreach($this->items as $id => $item) : 
        	$item->name = unserialize($item->name);
        	$item->name = $item->name[$lang->getTag()];
        	
        	$item->des = unserialize($item->des);
        	$item->des = $item->des[$lang->getTag()];
        	
            $images = '';
            if($item->image != ''):
                $images = '<img id="item_'.$item->id.'_img" class="thumb-img" alt="'.$item->name.'" title="'.$item->name.'" src="'.JURI::base().'wrd/image2/'.$item->image.'" />';
            else:
                $images = '';
            endif;
            
            $show = false;
            if($item->cash > 0):
                $show = true;    
            endif;
            ?>
                <div class="item-details">
                	<div class="image_section">
	                	<div class="silde">
							<div class="mosaic-overlay">
								<div class="stop">
									<div class="stop_content" ><a href="<?php echo JRoute::_('index.php?option=com_promotions&view=redemptions&layout=details&id='.$item->id.'&Itemid=174'); ?>"><?php echo $item->name; ?></a></div>
								</div>
								<br clear="all">
								<div class="sbottom">
									<div class="des"><?php echo mb_substr(strip_tags($item->des), 0,20,'utf-8').'...' ; ?></div>
									<br clear="all">
									<div class="view_more"><a href="<?php echo JRoute::_('index.php?option=com_promotions&view=redemptions&layout=details&id='.$item->id.'&Itemid=174'); ?>"><?php echo JText::_('WRD_PROMOTION_VIEW_MORE'); ?></a></div>
								</div>
							</div>
							<img class="item_detail_image" id="item_<?php echo $item->id ?>_img" class="thumb-img" alt="<?php echo $item->name ?>" title="<?php echo $item->name ?>" src="<?php echo JURI::base().'wrd/image2/'.$item->image; ?>">
							<div class="text">
					    		<div><?php echo $item->name; ?></div>
						    </div>
					    </div>
				    </div>
				    <div class="point_to_exchange">
				    	<?php if($show == true): ?>
						<label for="item_<?php echo $item->id; ?>_id_2"  >
				    		<input checked="checked" name="item_<?php echo $item->id; ?>_type" type="radio" id="item_<?php echo $item->id; ?>_id_2" value="2">
				    		<span class="custom radio"></span> 
				    		
				    		<font class="<?php echo ($item->quantity <= 0) ? "out_of_stock":""  ?>">
				    		
				    			<?php echo number_format($item->pointx,0,'.',','); ?> 
				  
				    			<?php echo JText::_('WRD_PROMOTION_POINTS'); ?> + 
				    		 
				    			<?php echo number_format($item->cash,0,'.',','); ?> 
				    		
				    			<?php echo JText::_('WRD_PROMOTION_VND'); ?>
				    		</font>
				    		
				    	</label>
						
						<input type="hidden" name="item_<?php echo $item->id ?>_id_2_qty" value="1" />
                        <input type="hidden" id="item_<?php echo $item->id ?>_id_2_point" value="<?php echo $item->point ?>" />
                        <input type="hidden" id="item_<?php echo $item->id ?>_id_2_pointx" value="<?php echo $item->pointx ?>" />
                        <input type="hidden" id="item_<?php echo $item->id ?>_id_2_cash" value="<?php echo $item->cash ?>" />
						<input type="hidden" id="item_<?php echo $item->id ?>_name"  name="item_<?php echo $item->id ?>_name" value="<?php echo $item->name; ?>" />
				    	<?php endif; ?>
			    	
			    		<?php if($item->point > 0): ?>
				    	<label for="item_<?php echo $item->id; ?>_id"  >
				    		<input checked="checked" name="item_<?php echo $item->id; ?>_type" type="radio" id="item_<?php echo $item->id; ?>_id" value="1">
				    		<span class="custom radio"></span> 
				    		
				    		<font class="<?php echo ($item->quantity <= 0) ? "out_of_stock":""  ?>">
				    			<?php echo number_format($item->point,0,'.',','); ?> 
				    			<?php echo JText::_('WRD_PROMOTION_POINTS'); ?>
				    		</font>
				    	</label>
				    	
				    	
				    	<input type="hidden" name="item_<?php echo $item->id; ?>_id_qty" value="1" />
						<input type="hidden" id="item_<?php echo $item->id ?>_id_point" value="<?php echo $item->point ?>" />
						<input type="hidden" id="item_<?php echo $item->id ?>_id_pointx" value="<?php echo $item->pointx ?>" />
						<input type="hidden" id="item_<?php echo $item->id ?>_id_cash" value="<?php echo $item->cash ?>" />
				    	<input type="hidden" id="item_<?php echo $item->id ?>_name"  name="item_<?php echo $item->id ?>_name" value="<?php echo $item->name; ?>" />
						<?php endif; ?>
						<input id="item_<?php echo $item->id; ?>" type="hidden" name="item_<?php echo $item->id; ?>" value="1" />
						<input id="item_<?php echo $item->id; ?>_soluong" type="hidden" name="item_<?php echo $item->id; ?>_soluong" value="<?php echo $item->quantity; ?>" />
						<input id="item_<?php echo $item->id; ?>_remain" type="hidden" value="<?php echo $item->quantity; ?>" />
				    </div>
				    <div class="true_price" style="padding-top:5px;">
			    	
						<label>(<?php echo JText::_('WRD_PROMOTION_VALUE') ?> 
						<?php echo number_format($item->price,0,'.',','); ?> 
						<?php echo JText::_('WRD_PROMOTION_VND'); ?>)</label>
			   
 					</div>
					<?php if($item->quantity <= 0): ?>
		     			<div class="fright" style="float: right; color: red;"><b><i>(<?php echo JText::_('WRD_PROMOTION_OUT_OF_STOCK'); ?>)</i></b></div>
		     		<?php else: ?>
		     			<?php if($this->user->id == 0): ?>
		     			<div class="add-to-cart-login"><a class="need_login" name="item_<?php echo $item->id; ?>" href="javascript:void(null);">
		     				<?php echo JText::_('WRD_PROMOTION_ADD_TO_CART'); ?></a></div>
			     		<?php else: ?>
			     			<div class="add-to-cart fright"><a name="item_<?php echo $item->id; ?>" href="javascript:void(null);">
			     				<?php echo JText::_('WRD_PROMOTION_ADD_TO_CART'); ?></a></div>
			     		<?php endif;?>
		     		<?php endif;?>

                </div>
          	<?php endforeach; ?>
			<br clear="both">
			<?php echo $this->pagination->getPagesLinks(); ?>
			<?php echo JHTML::_( 'form.token' ); ?>
    </form>
</div>

<input type="hidden" id="promotion-link" value="" />
<?php else:?>
	Empty
<?php endif; ?>